package com.siyoumi.interceptor;

import com.siyoumi.config.SysConfig;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.util.XDate;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.util.XLog;
import com.siyoumi.util.XStr;
import com.siyoumi.util.entity.ThreadLocalData;
import com.siyoumi.validator.XValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.time.LocalDateTime;

//拦截器
@Slf4j
public class CommonInterceptor
        extends InterceptorBase
        implements HandlerInterceptor {

    /**
     * 执行前
     *
     * @param request
     * @param response
     * @param handler
     * @return boolean
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //线程变量回收
        ThreadLocalData.remove();
        
        log.info("BEGIN");
        String url = XHttpContext.getUrl();
        log.info("URL: {}", url);
        log.info("URL_FULL: {}", XHttpContext.getUrlFull());
        XHttpContext.set("begin_date", XDate.now());

        //添加请求头
        //response.addHeader("Access-Control-Allow-Origin", "*");
        //response.addHeader("Access-Control-Allow-Credentials", "true");
        //response.addHeader("Access-Control-Allow-Headers", "DNT,Keep-Alive,User-Agent,Cache-Control,Content-Type,token");

        //设置x
        String x = XHttpContext.input("x", null);
        if (XStr.hasAnyText(x)) {
            XHttpContext.setX(x);
        }

        if (!SysConfig.getIns().isDev()) {
            //正式环境，不能访问含test的路由
            if (XStr.contains(url.toLowerCase(), "/test/")) {
                XValidator.err(EnumSys.ENV_ERR.getR("含有非法字符[test]"));
            }
        }

        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LocalDateTime beginDate = XHttpContext.get("begin_date");

        //线程变量回收
        ThreadLocalData.remove();

        Duration between = XDate.between(beginDate, XDate.now());
        log.info("exec_time: {}ms", between.toMillis());
        log.info("END");
    }
}
